﻿using Inaction;
using Inaction.Core;
using Inaction.Linq.Clause;
using Inaction.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Inaction.Linq
{
    public class LinqHelper<T> where T : Model<T>,new()
    {
        LinqRoot root = null;
        public string WhereSql { get; private set; }
        public List<ParaValue> Paras { get; private set; }
        public LinqHelper(Expression<Func<T, bool>> e)
        {
            if (e == null)
                root = new LinqRoot(typeof(T));
            else
            {
                root = new LinqRoot(e);
                var ret = LinqParse.Parse(e.Body, root);
                WhereSql = ret.GetClauseSql();
            }
            Paras = root.Paras;
        }

        #region 静态公有方法
        public static SqlStatement CreateSelectSql(Expression<Func<T, bool>> e)
        {
            return new LinqHelper<T>(e).GetSelecteSql();
        }

        public static SqlStatement CreateExecuteScalarSql(IProperty property, Expression<Func<T, bool>> e, string sqlClause)
        {
            return new LinqHelper<T>(e).GetExecuteScalarSql(property,sqlClause);
        }

        public static SqlStatement CreateExecuteScalarSql(Expression<Func<T, bool>> e, string sqlClause)
        {
            return new LinqHelper<T>(e).GetExecuteScalarSql(sqlClause);
        }
        #endregion

        #region 私有方法
        private SqlStatement GetExecuteScalarSql(IProperty property, string sqlClause)
        {
            return SqlStatement.CreateExecuteScalarSql(root.RootType, sqlClause, property, WhereSql, Paras);
        }

        private SqlStatement GetExecuteScalarSql(string sqlClause)
        {
            return SqlStatement.CreateExecuteScalarSql(root.RootType, sqlClause, WhereSql, Paras);
        }

        private SqlStatement GetSelecteSql()
        {
            return SqlStatement.CreateSelecte(root.RootType, WhereSql, Paras);
        }
        #endregion
    }
}
